import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver } from '@angular/core';
import * as _ from "lodash";
import { FlowInfoComponent } from '../../modal/flow-info/flow-info.component';
import { AppPaginationComponent, PaginationModel } from "../../../../../widgets/pagination/pagination.component";
import { DataInTransitPageService } from './data-in-transit-page.service'
import { DataService } from 'app/services/data.service';
import { Util } from '../../../../../common/util';
import { TablePageComponent } from '../../table/table-page/table-page.component';

@Component({
  selector: 'app-data-in-transit-page',
  templateUrl: './data-in-transit-page.component.html',
  styleUrls: ['./data-in-transit-page.component.scss'],
  providers: [DataInTransitPageService]
})
export class DataInTransitPageComponent implements OnInit {

  //在途数据列表
  @ViewChild("qdiitransitTablePage", { read: ViewContainerRef })
  qdiitransitTablePage: ViewContainerRef;
  tablePageComponent: ComponentRef<TablePageComponent>;
  @ViewChild("flowInfo", { read: ViewContainerRef })
  flowInfo: ViewContainerRef;
  flowInfoComponent: ComponentRef<FlowInfoComponent>;

  //克隆列表
  public cloneList: any = [];
  // lodash
  public _: any = _;
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  public listData: any;

  //分页配置
  public listPageInfo = {
    currentPageNum: 1,
    pageSize: 50,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  //列表全选
  public isCheckedAll: any = false;

  //查询列表getBody
  public getBody: any = {
    pageIndex: '',
    pageSize: '',
    sOprDateStart: '',//发起日期起始区间
    sOprDateEnd: '',//发起日期结束区间
    commitOprZh: '',//提交人
    sFileName: '',// 文件名称
    nBatchNoStart: '',//批次号起始区间
    nBatchNoEnd: '',// 批次号结束区间
    // sFundType: '',//适用基金类别
    // sFundGroupds: '',//适用基金组
  };


  constructor(public resolver: ComponentFactoryResolver,
    public dataInTransitService: DataInTransitPageService,
    public dataService: DataService,
  ) { }

  ngOnInit() {
    let that = this;
    this.loadlist();
    // 权限处理
    this.dataService.initTree.subscribe((data) => {
      if (data) {
        let SessionMenuData = sessionStorage.getItem('menu');
        this.menuData = JSON.parse(SessionMenuData)
        this.menuResourceSet = [];
        _.forEach(this.menuData, (item, index) => {
          if (item.sName == '风控管理') {
            _.forEach(item.children, (it, idx) => {
              if (it.sName == 'QDII条目管理') {
                _.forEach(it.children, (ite, i) => {
                  if (ite.sName == '在途数据') {
                    that.menuResourceSet = ite.resourceSet
                    sessionStorage.setItem('btn-QDII', this.menuResourceSet);
                  }
                })
              }
            })
          }
        })
      }
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '风控管理') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == 'QDII条目管理') {
            _.forEach(it.children, (ite, i) => {
              if (ite.sName == '在途数据') {
                that.menuResourceSet = ite.resourceSet
                sessionStorage.setItem('btn-QDII', this.menuResourceSet);
              }
            })
          }
        })
      }
    })
    console.info(this.menuResourceSet)
  }

  // 条数分页
  sizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.loadlist();
    }
  }
  // 列表分页
  pageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.loadlist(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }

  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.listData.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  //分页列表
  loadlist(pageNum?, pageSize?) {
    let that = this;
    this.isCheckedAll = false;
    this.getBody.sOpr = _.trim(this.getBody.sOpr);
    this.getBody.sFileName = _.trim(this.getBody.sFileName);
    this.getBody.nBatchNoStart = _.trim(this.getBody.nBatchNoStart);
    this.getBody.nBatchNoEnd = _.trim(this.getBody.nBatchNoEnd);
    this.getBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    this.getBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    this.dataInTransitService.list(this.getBody).subscribe(data => {
      if (data) {
        console.log(data);
        this.listData = data.list;
        this.cloneList = _.cloneDeep(data.list);
        this.controlDom();
        this.showTablePage(this.listData)
        this.listPageInfo.currentPageNum = data.pageNum;
        this.listPageInfo.totalPages = data.pages;
        this.listPageInfo.total = data.total;
        this.listPageInfo.startRow = data.startRow;
        this.listPageInfo.endRow = data.endRow;
       
      }
    })
  }
  // 显示modal
  showModal() {
    let that = this;
    let checkProduct = [];
    _.forEach(this.listData, item => {
      if (item.isChecked) {
        checkProduct.push(item);
      }
    });
    if (checkProduct.length == 1) {
      if (this.flowInfoComponent && this.flowInfoComponent.instance) {
        this.flowInfoComponent.destroy();
      }

      // 动态创建组件的实例
      const flowInfoComponent = this.resolver.resolveComponentFactory(FlowInfoComponent);
      this.flowInfoComponent = this.flowInfo.createComponent(flowInfoComponent);
      this.flowInfoComponent.instance.item = checkProduct[0];
      window['$']('#modal1').modal('show');
    } else {
      window["swal"]("提示", "请选择一条记录！", "warning");
    }

  }

  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) {
      // 更新为全选
      _.forEach(this.listData, item => {
        item.isChecked = true;
      });
    } else {
      // 更新为不全选
      _.forEach(this.listData, item => {
        item.isChecked = false;
      });
    }
  }
  //搜索查询
  searchQuery() {
    let that = this;
    if (Util.dateOrder(that.getBody.sOprDateStart, that.getBody.sOprDateEnd)) {
      if (that.getBody.nBatchNoEnd != '' && that.getBody.nBatchNoStart != '') {
        if (parseInt(that.getBody.nBatchNoEnd) > parseInt(that.getBody.nBatchNoStart)) {
          that.loadlist(1);
        } else {
          window['swal']("提示", "起始批次 须小于 结束批次", "warning");
        }
      } else {
        that.loadlist(1);
      }
    } else {
      window['swal']("提示", "发行日期 须早于 到期日期", "warning");
    }
  }
  //根据编号是否相同操控dom
  controlDom() {
    let that = this;
    if (this.listData != undefined) {
      for (let i = 0; i < that.listData.length - 1; i++) {
        if (that.listData[i].nQjId == that.listData[i + 1].nQjId) {
          _.forIn(that.listData[i], (item1, key1) => {
            let index1 = i + 1;
            let index2 = i + 2;
            let id1 = "#transitTable tbody tr:nth-child(" + index1 + ") td div[name=" + key1 + "]";
            let id2 = "#transitTable tbody tr:nth-child(" + index2 + ") td div[name=" + key1 + "]";
            // let id3 = "#review-table tbody tr:nth-child(" + index1 + ") td select[name=" + key1 + "]";
            // let id4 = "#review-table tbody tr:nth-child(" + index2 + ") td select[name=" + key1 + "]";
            if (item1 == that.listData[i + 1][key1]) {
              // window['$'](id1).removeClass('font-color');
              // window['$'](id2).removeClass('font-color');
              // window['$'](id3).removeClass('font-color');
              // window['$'](id4).removeClass('font-color');
            } else {
              // window['$'](id1).removeClass('font-color');
              // window['$'](id3).removeClass('font-color');
              that.cloneList[i + 1][key1] = 'red';
            }
          })
        }
      }
    }
    else {
      this.controlDom();
    }
  }
  // 点击表格头排序
  orderData(colName) {
    let listDataAsc = _.orderBy(this.listData, [colName], ["asc"]);
    if (JSON.stringify(this.listData) == JSON.stringify(listDataAsc)) {
      listDataAsc = _.orderBy(this.listData, [colName], ["desc"]);
    }
    this.listData = listDataAsc;
  }
  //在途数据列表
  showTablePage(item) {
    // 判断组件是否已创建，如果创建先注销
    if (this.tablePageComponent && this.tablePageComponent.instance) {
      this.tablePageComponent.destroy();
    }

    // 动态创建组件的实例
    const tablePageComponent = this.resolver.resolveComponentFactory(TablePageComponent);
    this.tablePageComponent = this.qdiitransitTablePage.createComponent(tablePageComponent);
    this.tablePageComponent.instance.listData = item;
    this.tablePageComponent.instance.listType = '4';
    this.tablePageComponent.instance.setColor = this.cloneList;
  }
}
